package com.example.sm.mycook.widget;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

import com.handmark.pulltorefresh.library.PullToRefreshBase;

/**
 * Created by Administrator on 2016/12/5.
 */
public class HomeRefreshRecycleView  extends PullToRefreshBase<RecyclerView>{


    public HomeRefreshRecycleView(Context context) {
        super(context);
    }

    public HomeRefreshRecycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public Orientation getPullToRefreshScrollDirection() {
        return Orientation.VERTICAL;
    }

    @Override
    protected RecyclerView createRefreshableView(Context context, AttributeSet attrs) {
        RecyclerView recyclerView=new RecyclerView(context,attrs);

        return recyclerView;
    }

    @Override
    protected boolean isReadyForPullEnd() {
        RecyclerView recyclerView=getRefreshableView();

        //获取item的条数
        int childCount = recyclerView.getChildCount();

        if (childCount==0)
            return  false;
        //获取最后的item
        View child = recyclerView.getChildAt(childCount-1);
        //控件的总高度
        int heigth = recyclerView.getHeight();
        //获取控件的底部内边距
        int paddingBottom = recyclerView.getPaddingBottom();
        //获取最后的item的外边距
        MarginLayoutParams params = (MarginLayoutParams) child.getLayoutParams();
        int bottomMagin= params.bottomMargin;

        //最后的item的底部距离顶部的值
        int bottom = child.getBottom();

        //获取总的item数量
        int itemCount = recyclerView.getAdapter().getItemCount();

        //获取当前item在adapter的位置
        int childAdapterPos = recyclerView.getChildAdapterPosition(child);

        //判断是否到底端
        return heigth == bottom+bottomMagin+paddingBottom&&childAdapterPos+1==itemCount;
    }

    @Override
    protected boolean isReadyForPullStart() {
        //获取刷新的View
        RecyclerView recyclerView = getRefreshableView();
        //获取第一个item   View
        View child = recyclerView.getChildAt(0);
        if (child!=null) {
            //第一个item到顶端的距离
            int top = child.getTop();
            //获取控件的内边距
            int paddingTop = recyclerView.getPaddingTop();
            //获取第一条item的外边距
            MarginLayoutParams params = (MarginLayoutParams) child.getLayoutParams();
            int topMargin = params.topMargin;

            return top == topMargin + paddingTop;
        }
        return  false;
    }
}
